#include "scrollview.h"

#include "lualib.h"
#include "lua.h"
#include "lauxlib.h"

#include <string.h>
#include <stdio.h>
#include <memory.h>
#include <stdlib.h>

extern lua_State* g_ufo_lua_state;

static int lua_ufoScrollViewSetContentSize(lua_State *L)
{
	UFO_View view = *(UFO_View*)luaL_checkudata(L, 1, "ufo.ufoView");
	int width = lua_tonumber(L, 2);
	int height = lua_tonumber(L, 3);
	lua_pushinteger(L, ufoScrollViewSetContentSize(view, width, height));
	return 1;
}

static int lua_ufoScrollViewSetContentOffset(lua_State *L)
{
	UFO_View view = *(UFO_View*)luaL_checkudata(L, 1, "ufo.ufoView");
	int x = lua_tonumber(L, 2);
	int y = lua_tonumber(L, 3);
	int animated = lua_toboolean(L, 3);
	lua_pushinteger(L, ufoScrollViewSetContentOffset(view, x, y, animated));
	return 1;
}

static int lua_ufoScrollViewGetContentOffset(lua_State *L)
{
	UFO_View view = *(UFO_View*)luaL_checkudata(L, 1, "ufo.ufoView");
	int x = 0, y = 0;
	lua_pushinteger(L, ufoScrollViewGetContentOffset(view, &x, &y));
	lua_pushinteger(L, x);
	lua_pushinteger(L, y);
	return 2;
}

static int lua_ufoScrollViewGetContentSize(lua_State *L)
{
	UFO_View view = luaL_checkudata(L, 1, "ufo.ufoView");
	int width = 0, height = 0;
	lua_pushinteger(L, ufoScrollViewGetContentSize(view, &width, &height));
	lua_pushinteger(L, width);
	lua_pushinteger(L, height);
	return 2;
}

static int lua_ufoScrollViewShowsHorizontalScrollIndicator(lua_State *L)
{
	UFO_View view = *(UFO_View*)luaL_checkudata(L, 1, "ufo.ufoView");
	int bShow = lua_toboolean(L, 2);
    
	lua_pushinteger(L, ufoScrollViewShowsHorizontalScrollIndicator(view, bShow));
	return 1;
}

static int lua_ufoScrollViewShowsVerticalScrollIndicator(lua_State *L)
{
	UFO_View view = *(UFO_View*)luaL_checkudata(L, 1, "ufo.ufoView");
	int bShow = lua_toboolean(L, 2);

	lua_pushinteger(L, ufoScrollViewShowsVerticalScrollIndicator(view, bShow));
	return 1;
}

static const struct luaL_Reg scrollviewlib [] = {
	{"setContentSize", lua_ufoScrollViewSetContentSize},
	{"getContentSize", lua_ufoScrollViewGetContentSize},
	{"setContentOffset", lua_ufoScrollViewSetContentOffset},
	{"getContentOffset", lua_ufoScrollViewGetContentOffset},
   	{"showsHorizontalScrollIndicator", lua_ufoScrollViewShowsHorizontalScrollIndicator},
	{"showsVerticalScrollIndicator", lua_ufoScrollViewShowsVerticalScrollIndicator},
	{0, 0},
};

int internal_initializationScript_scrollview()
{
	if (!g_ufo_lua_state) {
		g_ufo_lua_state = luaL_newstate();
		luaL_openlibs(g_ufo_lua_state);
	}

	luaL_newmetatable(g_ufo_lua_state, "ufo.ufoView");

	lua_pushvalue(g_ufo_lua_state, -1);
	lua_setfield(g_ufo_lua_state, -2, "__index");

	luaL_register(g_ufo_lua_state, 0, scrollviewlib);

	return 1;
}